<template>
  <div class="resource-property-tab">
    <div class="tab-content">
      <div class="section-header">
        <h3>资源属性</h3>
        <div class="header-actions">
          <Button type="primary" @click="openPropertyManager">
            <IconifyIcon icon="ant-design:setting-outlined" />
            属性管理 (原版)
          </Button>
          <Button type="primary" @click="openPropertyManagerV2">
            <IconifyIcon icon="ant-design:setting-outlined" />
            属性管理 (useVbenForm版)
          </Button>
          <Button type="primary" @click="openPropertyManagerV3">
            <IconifyIcon icon="ant-design:setting-outlined" />
            属性管理 (FormCreate可视化版)
          </Button>
          <Button type="primary" @click="openPropertyDataEditor">
            <IconifyIcon icon="ant-design:edit-outlined" />
            属性数据编辑
          </Button>
          <Button @click="openPropertyPreview" :disabled="!hasProperties">
            <IconifyIcon icon="ant-design:eye-outlined" />
            属性分析
          </Button>
          <Button @click="openFormPreview" :disabled="!hasProperties">
            <IconifyIcon icon="ant-design:form-outlined" />
            表单预览
          </Button>
          <Button @click="openMultiDomainManager" type="primary" ghost>
            <IconifyIcon icon="ant-design:appstore-outlined" />
            多领域管理
          </Button>
<!--          <Button @click="openMultiDomainTest" type="dashed">-->
<!--            <IconifyIcon icon="ant-design:experiment-outlined" />-->
<!--            测试数据加载-->
<!--          </Button>-->
        </div>
      </div>

      <!-- 属性展示网格 -->
      <div class="properties-grid">
        <div
          v-for="(value, key) in paginatedProperties"
          :key="key"
          class="property-item"
        >
          <div class="property-label">{{ getPropertyLabel(key) }}</div>
          <div class="property-value">
            <div v-if="Array.isArray(value)" class="array-value">
              <Tag
                v-for="item in value"
                :key="item"
                color="blue"
                class="array-tag"
              >
                {{ item }}
              </Tag>
            </div>
            <div v-else-if="typeof value === 'boolean'" class="boolean-value">
              <Tag :color="value ? 'green' : 'red'">
                {{ value ? '是' : '否' }}
              </Tag>
            </div>
            <div v-else-if="typeof value === 'number'" class="number-value">
              {{ formatNumberValue(key, value) }}
            </div>
            <div v-else class="string-value">
              {{ value }}
            </div>
          </div>
          <div class="property-meta">
            <Tag v-if="isRequired(key)" color="red" size="small">必填</Tag>
            <Tag :color="getPropertyTypeColor(key)" size="small">
              {{ getPropertyType(key) }}
            </Tag>
          </div>
        </div>
      </div>

      <!-- 分页组件 -->
      <div v-if="hasProperties" class="pagination-wrapper">
        <Pagination
          v-model:current="currentPage"
          :total="totalProperties"
          :page-size="pageSize"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="
            (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条属性`
          "
          @change="handlePageChange"
          @show-size-change="handlePageSizeChange"
        />
      </div>

      <!-- 属性为空时的提示 -->
      <div v-if="!hasProperties" class="empty-state">
        <IconifyIcon icon="ant-design:inbox-outlined" class="empty-icon" />
        <p>暂无属性数据</p>
        <Button type="primary" @click="openPropertyDataEditor">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加属性
        </Button>
      </div>
    </div>

    <!-- 属性管理模态框 -->
    <Modal
      v-model:visible="propertyManagerVisible"
      title="资源属性管理"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManager
        v-if="propertyManagerVisible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性管理模态框 (useVbenForm版) -->
    <Modal
      v-model:visible="propertyManagerV2Visible"
      title="资源属性管理 (useVbenForm版)"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManagerV2
        v-if="propertyManagerV2Visible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性管理模态框 (FormCreate可视化版) -->
    <Modal
      v-model:visible="propertyManagerV3Visible"
      title="资源属性管理 (FormCreate可视化版)"
      width="95%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManagerV3
        v-if="propertyManagerV3Visible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性数据编辑器模态框 -->
    <Modal
      v-model:visible="propertyDataEditorVisible"
      title="资源属性数据编辑"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyDataEditor
        v-if="propertyDataEditorVisible"
        :resource="resource"
        @update="onPropertyUpdate"
        @configureSchema="openPropertyManager"
      />
    </Modal>

    <!-- 表单预览模态框 -->
    <Modal
      v-model:visible="formPreviewVisible"
      title="VbenForm 表单预览"
      width="900px"
      :footer="null"
      :destroyOnClose="true"
    >
      <PropertyFormPreview
        v-if="formPreviewVisible"
        :schema="propertySchema"
        :data="propertyData"
        @form-change="handleFormDataChange"
      />
    </Modal>

    <!-- 属性预览模态框 -->
    <Modal
      v-model:visible="propertyPreviewVisible"
      title="资源属性分析"
      width="800px"
      :footer="null"
      :destroyOnClose="true"
    >
      <div class="property-preview">
        <div class="preview-header">
          <h4>基于当前属性Schema的表单预览</h4>
          <p class="preview-description">
            此预览展示了根据资源属性Schema生成的表单界面
          </p>
        </div>

        <div class="preview-content">
          <div class="schema-info">
            <h5>Schema信息</h5>
            <div class="schema-stats">
              <Tag color="blue">字段数量: {{ propertySchema.length }}</Tag>
              <Tag color="green">必填字段: {{ requiredFieldsCount }}</Tag>
              <Tag color="orange">可选字段: {{ optionalFieldsCount }}</Tag>
            </div>
          </div>

          <div class="form-preview">
            <h5>表单预览</h5>
            <div class="form-placeholder">
              <div
                class="form-item"
                v-for="field in propertySchema"
                :key="field.fieldName"
              >
                <div class="form-label">
                  <span class="label-text">{{ field.label }}</span>
                  <Tag
                    v-if="field.rules === 'required'"
                    color="red"
                    size="small"
                    >必填</Tag
                  >
                </div>
                <div class="form-control">
                  <div class="control-placeholder">
                    <IconifyIcon :icon="getComponentIcon(field.component)" />
                    <span>{{ getComponentName(field.component) }}</span>
                    <span
                      v-if="field.componentProps?.placeholder"
                      class="placeholder-text"
                    >
                      {{ field.componentProps.placeholder }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="data-preview">
            <h5>当前数据</h5>
            <div class="data-content">
              <pre>{{ JSON.stringify(propertyData, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 多领域属性管理模态框 -->
    <Modal
      :visible="multiDomainManagerVisible"
      title="多领域属性管理"
      width="95%"
      :footer="null"
      :destroyOnClose="true"
      @update:visible="multiDomainManagerVisible = $event"
    >
      <MultiDomainPropertyManager
        v-if="multiDomainManagerVisible"
        :resource-id="resource?.id"
        @properties-update="handleMultiDomainUpdate"
      />
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { Button, Modal, message, Tag, Pagination } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import ResourcePropertyManager from './ResourcePropertyManager.vue';
import ResourcePropertyManagerV2 from './ResourcePropertyManagerV2.vue';
import ResourcePropertyManagerV3 from './ResourcePropertyManagerV3.vue';
import ResourcePropertyDataEditor from './ResourcePropertyDataEditor.vue';
import PropertyFormPreview from './PropertyFormPreview.vue';
import MultiDomainPropertyManager from './MultiDomainPropertyManager.vue';

interface Resource {
  id?: string | number;
  name?: string;
  properties?: string;
  [key: string]: any;
}

const props = defineProps<{
  resource?: Resource;
}>();

const emit = defineEmits<{
  'property-update': [properties: any];
}>();

// 属性管理相关状态
const propertyManagerVisible = ref(false);
const propertyManagerV2Visible = ref(false);
const propertyManagerV3Visible = ref(false);
const propertyDataEditorVisible = ref(false);
const propertyPreviewVisible = ref(false);
const formPreviewVisible = ref(false);
const multiDomainManagerVisible = ref(false);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);

// 解析属性数据
const parsedProperties = computed(() => {
  if (!props.resource?.properties) return {};
  try {
    const properties = JSON.parse(props.resource.properties);
    return typeof properties === 'object' ? properties : {};
  } catch (error) {
    console.error('解析属性数据失败:', error);
    return {};
  }
});

// 解析属性Schema
const propertySchema = computed(() => {
  const properties = parsedProperties.value;
  if (properties.schema && Array.isArray(properties.schema)) {
    return properties.schema;
  }
  return [];
});

// 解析属性数据
const propertyData = computed(() => {
  const properties = parsedProperties.value;
  if (properties.data && typeof properties.data === 'object') {
    return properties.data;
  }
  // 兼容旧格式
  return parsedProperties.value;
});

// 是否有属性数据
const hasProperties = computed(() => {
  return Object.keys(propertyData.value).length > 0;
});

// 分页相关计算属性
const totalProperties = computed(() => {
  return Object.keys(propertyData.value).length;
});

const totalPages = computed(() => {
  return Math.ceil(totalProperties.value / pageSize.value);
});

const paginatedProperties = computed(() => {
  const properties = propertyData.value;
  const keys = Object.keys(properties);
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  const paginatedKeys = keys.slice(startIndex, endIndex);

  const result: Record<string, any> = {};
  paginatedKeys.forEach((key) => {
    result[key] = properties[key];
  });

  return result;
});

// 获取属性标签
const getPropertyLabel = (key: string) => {
  const schema = propertySchema.value;
  const field = schema.find((item: any) => item.fieldName === key);

  if (field?.label) {
    return field.label;
  }

  // 如果没有找到schema，尝试从字段名生成中文标签
  const labelMap: Record<string, string> = {
    building_type: '建筑类型',
    floors: '楼层数',
    total_rooms: '房间总数',
    construction_year: '建造年份',
    building_area: '建筑面积',
    parking_spaces: '停车位数量',
    facilities: '配套设施',
    service_quality: '服务质量等级',
    building_status: '建筑状态',
    apartment_type: '公寓类型',
    rental_period: '租赁周期',
    // 添加更多字段映射
  };

  return labelMap[key] || key;
};

// 获取属性类型
const getPropertyType = (key: string) => {
  const schema = propertySchema.value;
  const field = schema.find((item: any) => item.fieldName === key);
  if (!field) return 'string';

  switch (field.component) {
    case 'InputNumber':
      return 'number';
    case 'Select':
      return field.componentProps?.mode === 'multiple' ? 'array' : 'select';
    case 'Switch':
      return 'boolean';
    default:
      return 'string';
  }
};

// 获取属性类型颜色
const getPropertyTypeColor = (key: string) => {
  const type = getPropertyType(key);
  const colorMap: Record<string, string> = {
    string: 'blue',
    number: 'green',
    boolean: 'orange',
    array: 'purple',
    select: 'cyan',
  };
  return colorMap[type] || 'default';
};

// 是否必填
const isRequired = (key: string) => {
  const schema = propertySchema.value;
  const field = schema.find((item: any) => item.fieldName === key);
  return field?.rules === 'required';
};

// 格式化数字值
const formatNumberValue = (key: string, value: number) => {
  const schema = propertySchema.value;
  const field = schema.find((item: any) => item.fieldName === key);
  const addonAfter = field?.componentProps?.addonAfter;

  if (addonAfter) {
    return `${value} ${addonAfter}`;
  }

  // 特殊格式化
  if (key === 'building_area') {
    return `${value.toLocaleString()} 平方米`;
  }

  return value.toString();
};

// 属性管理方法
const openPropertyManager = () => {
  propertyManagerVisible.value = true;
};

const openPropertyManagerV2 = () => {
  propertyManagerV2Visible.value = true;
};

const openPropertyManagerV3 = () => {
  propertyManagerV3Visible.value = true;
};

const openPropertyDataEditor = () => {
  propertyDataEditorVisible.value = true;
};

const onPropertyUpdate = (data: any) => {
  message.success('属性更新成功');
  emit('property-update', data);
  console.log('属性更新:', data);
};

// 表单数据变化处理
const handleFormDataChange = (values: Record<string, any>) => {
  console.log('表单数据变化:', values);
  // 可以在这里处理表单数据变化，比如实时保存
};

// 分页事件处理方法
const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
};

// 预览相关方法
const openPropertyPreview = () => {
  propertyPreviewVisible.value = true;
};

const openFormPreview = () => {
  formPreviewVisible.value = true;
};

const openMultiDomainManager = () => {
  multiDomainManagerVisible.value = true;
};

const handleMultiDomainUpdate = (properties: any) => {
  console.log('多领域属性更新:', properties);
  message.success('多领域属性更新成功');
  emit('property-update', properties);
};

// 预览相关计算属性
const requiredFieldsCount = computed(() => {
  return propertySchema.value.filter((field: any) => field.rules === 'required')
    .length;
});

const optionalFieldsCount = computed(() => {
  return propertySchema.value.filter((field: any) => field.rules !== 'required')
    .length;
});

const getComponentIcon = (component: string) => {
  const iconMap: Record<string, string> = {
    Input: 'ant-design:edit-outlined',
    InputNumber: 'ant-design:number-outlined',
    Select: 'ant-design:down-outlined',
    Switch: 'ant-design:check-square-outlined',
    DatePicker: 'ant-design:calendar-outlined',
    Textarea: 'ant-design:file-text-outlined',
    Upload: 'ant-design:upload-outlined',
  };
  return iconMap[component] || 'ant-design:question-outlined';
};

const getComponentName = (component: string) => {
  const nameMap: Record<string, string> = {
    Input: '输入框',
    InputNumber: '数字输入框',
    Select: '选择器',
    Switch: '开关',
    DatePicker: '日期选择器',
    Textarea: '多行文本',
    Upload: '文件上传',
  };
  return nameMap[component] || '未知组件';
};
</script>

<style scoped>


/* 响应式设计 */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-actions {
    justify-content: flex-start;
    width: 100%;
  }

  .properties-grid {
    grid-template-columns: 1fr;
  }
}

.resource-property-tab {
  padding: 16px;
}

.tab-content {
  min-height: 400px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.header-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.properties-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.property-item {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.property-item:hover {
  background: #f5f5f5;
  border-color: #d9d9d9;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.property-label {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.property-value {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
  color: #595959;
  word-break: break-word;
}

.array-value {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.array-tag {
  margin: 2px;
}

.boolean-value {
  display: inline-block;
}

.number-value {
  font-weight: 500;
  color: #1890ff;
}

.string-value {
  color: #595959;
}

.property-meta {
  display: flex;
  gap: 4px;
  margin-top: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding-top: 16px;
  margin-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #8c8c8c;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
  color: #d9d9d9;
}

.empty-state p {
  margin: 0 0 16px;
  font-size: 16px;
}

/* 预览模态框样式 */
.property-preview {
  padding: 20px;
}

.preview-header {
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-header h4 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.preview-description {
  margin: 0;
  font-size: 14px;
  color: #8c8c8c;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.schema-info {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.schema-info h5 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.schema-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.form-preview {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.form-preview h5 {
  margin: 0 0 16px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.form-placeholder {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-label {
  display: flex;
  gap: 8px;
  align-items: center;
}

.label-text {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
}

.form-control {
  min-height: 32px;
}

.control-placeholder {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 6px 12px;
  font-size: 14px;
  color: #8c8c8c;
  background: #f5f5f5;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.placeholder-text {
  font-style: italic;
  color: #bfbfbf;
}

.data-preview {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.data-preview h5 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.data-content {
  max-height: 200px;
  padding: 12px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.data-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #595959;
  word-break: break-all;
  white-space: pre-wrap;
}
</style>
